﻿#include "TCP_ClientMode.h"
#include <QDebug>
#include <QHostAddress>

#define DEBUGinfo qDebug()

TCP_Client::TCP_Client()
{
    //分配空间，指定父对象
    MySocket = new QTcpSocket(this);
    connect(MySocket,&QTcpSocket::connected,this,&TCP_Client::ConnectionBuilt);
    connect(MySocket,&QTcpSocket::readyRead,this,&TCP_Client::ReadMessage);
    connect(MySocket,&QTcpSocket::disconnected,this,&TCP_Client::ConnectionClosed);
}
TCP_Client::~TCP_Client()
{
    if(MySocket->state() == QAbstractSocket::ConnectedState)
    {
        MySocket->close();
    }
}

//连接TCP服务器
bool TCP_Client::ConnectToServer(QString Server_ip, quint16 Server_port)
{
    MySocket->connectToHost(QHostAddress(Server_ip),Server_port);
    return MySocket->waitForConnected();
}
//bool TCP_Client::ConnectToServer(QString Local_ip, QString Server_ip, quint16 Server_port)
//{
//    if(!MySocket->bind(QHostAddress(Local_ip)))
//        return false;
//    MySocket->connectToHost(QHostAddress(Server_ip),Server_port);
//    return MySocket->waitForConnected();
//}
//断开连接
void TCP_Client::DisconnectFromServer()
{
    MySocket->close();
}
//发送消息
void TCP_Client::SendMessage(QByteArray msg)
{
    MySocket->write(msg);
}
//接收消息
void TCP_Client::ReadMessage()
{
    QByteArray ReciveMessage = MySocket->readAll();
    emit TcpClientModeMsg(ReciveMessage);
}

